package com.yaocw.baseproject.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.yaocw.baseproject.R;
import com.yaocw.baseproject.activity.WebActivity;
import com.yaocw.baseproject.adapter.NewsAdapter;
import com.yaocw.baseproject.entity.NewsEntity;
import com.yaocw.baseproject.entity.NewsListResponse;

import java.util.ArrayList;
import java.util.List;

public class NewsFragment extends BaseFragment {

    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private NewsAdapter newsAdapter;
    private List<NewsEntity> datas = new ArrayList<>();
    private int pageNum = 1;
    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                newsAdapter.setDatas(datas);
                newsAdapter.notifyDataSetChanged();
            }
        }
    };

    public static NewsFragment newInstance() {
        return new NewsFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_news;
    }

    @Override
    protected void initView() {
        recyclerView = mRootView.findViewById(R.id.recycler_view);
        refreshLayout = mRootView.findViewById(R.id.refresh_layout);
    }

    @Override
    protected void initData() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        newsAdapter = new NewsAdapter(getActivity());
        recyclerView.setAdapter(newsAdapter);

        newsAdapter.setOnItemClickListener(obj -> {
            NewsEntity newsEntity = (NewsEntity) obj;
            String url = "http://www.baidu.com";
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            navigateToWithBundle(WebActivity.class, bundle);
        });

        refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageNum = 1;
            getNewsList(true);
        });

        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            pageNum++;
            getNewsList(false);
        });

        getNewsList(true);
    }

    private void getNewsList(final boolean isRefresh) {
        String res = "{\"msg\" : \"success\",\n" +
                "     \"code\" : 0,\n" +
                "     \"page\" : {\"totalCount\":8,\"pageSize\":4,\"totalPage\":2,\"currPage\":1,\"list\":[{\"newsId\":1,\"newsTitle\":\"《忍者蛙》发售日公布 已上架Steam、支持简中\",\"authorName\":\"3DMGAME\",\"headerUrl\":\"https://p9.pstatp.com/thumb/6eed00026c4eac713a44\",\"commentCount\":3,\"releaseDate\":\"2020-07-31 22:23:00\",\"type\":1,\"thumbEntities\":[{\"thumbId\":1,\"thumbUrl\":\"http://p1-tt.byteimg.com/large/pgc-image/S6KR5958Y5X2Qt?from=pc\",\"newsId\":1}]},{\"newsId\":2,\"newsTitle\":\"外媒爆料：育碧\\u201c阿瓦隆\\u201d项目胎死腹中，只因为他不喜欢奇幻游戏\",\"authorName\":\"爱游戏的萌博士\",\"headerUrl\":\"https://p3.pstatp.com/thumb/43310001daafa9723ddf\",\"commentCount\":1,\"releaseDate\":\"2020-07-31 21:01:17\",\"type\":2,\"thumbEntities\":[{\"thumbId\":2,\"thumbUrl\":\"http://p1-tt.byteimg.com/large/pgc-image/714415d37865444ca2bef51eb1706cda?from=pc\",\"newsId\":2},{\"thumbId\":3,\"thumbUrl\":\"http://p1-tt.byteimg.com/large/pgc-image/33b9831739764bdb8a157efce048ec85?from=pc\",\"newsId\":2},{\"thumbId\":4,\"thumbUrl\":\"http://p3-tt.byteimg.com/large/pgc-image/c8a4e737b54d41c1a84722fc1c6d191d?from=pc\",\"newsId\":2}]},{\"newsId\":3,\"newsTitle\":\"索尼公布Ready for PlayStation 5电视阵容\",\"authorName\":\"游戏时光VGtime\",\"headerUrl\":\"https://p1.pstatp.com/thumb/dc0c0004c450216ab2f3\",\"commentCount\":6,\"releaseDate\":\"2020-07-30 13:11:32\",\"type\":3,\"thumbEntities\":[{\"thumbId\":5,\"thumbUrl\":\"http://p6-tt.byteimg.com/large/pgc-image/S6CLixgC4HSrXD?from=pc\",\"newsId\":3}]},{\"newsId\":4,\"newsTitle\":\"一部不受关注的互动电影佳作\\u2014\\u2014解构《暴雨》\",\"authorName\":\"瑾瑜游乐说\",\"headerUrl\":\"https://sf3-ttcdn-tos.pstatp.com/img/pgc-image/e200b9de317b4e73af24299ea063bec2~120x256.image\",\"commentCount\":12,\"releaseDate\":\"2020-07-30 13:11:32\",\"type\":3,\"thumbEntities\":[{\"thumbId\":6,\"thumbUrl\":\"http://p6-tt.byteimg.com/large/pgc-image/17fe1be328e149c9aa400dcf8a8c4dd6?from=pc\",\"newsId\":4}]}]}\n" +
                "     }";

        if (isRefresh) {
            refreshLayout.finishRefresh(true);
        } else {
            refreshLayout.finishLoadMore(true);
        }
        NewsListResponse response = new Gson().fromJson(res, NewsListResponse.class);
        if (response != null && response.getCode() == 0) {
            List<NewsEntity> list = response.getPage().getList();
            if (list != null && list.size() > 0) {
                if (isRefresh) {
                    datas = list;
                } else {
                    datas.addAll(list);
                }
                mHandler.sendEmptyMessage(0);
            } else {
                if (isRefresh) {
                    showToastSync("暂时无数据");
                } else {
                    showToastSync("没有更多数据");
                }
            }
        }


//        HashMap<String, Object> params = new HashMap<>();
//        params.put("page", pageNum);
//        params.put("limit", RequestConfig.PAGE_SIZE);
//        Request.config(RequestConfig.BASE_URl, params).getRequest(Objects.requireNonNull(getActivity()), new RequestCallback() {
//            @Override
//            public void onSuccess(final String res) {
//                if (isRefresh) {
//                    refreshLayout.finishRefresh(true);
//                } else {
//                    refreshLayout.finishLoadMore(true);
//                }
//                NewsListResponse response = new Gson().fromJson(res, NewsListResponse.class);
//                if (response != null && response.getCode() == 0) {
//                    List<NewsEntity> list = response.getPage().getList();
//                    if (list != null && list.size() > 0) {
//                        if (isRefresh) {
//                            datas = list;
//                        } else {
//                            datas.addAll(list);
//                        }
//                        mHandler.sendEmptyMessage(0);
//                    } else {
//                        if (isRefresh) {
//                            showToastSync("暂时无数据");
//                        } else {
//                            showToastSync("没有更多数据");
//                        }
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Exception e) {
//                if (isRefresh) {
//                    refreshLayout.finishRefresh(true);
//                } else {
//                    refreshLayout.finishLoadMore(true);
//                }
//            }
//    });
    }
}